﻿/**
 * ...
 * @author Sergey Mamyan
 */

package tx.squirrel.neko.facebook.handler;

import mtwin.web.Request;
import neko.Web;
import tx.facebook.core.Facebook;
import tx.squirrel.neko.admin.model.Application;
import tx.squirrel.neko.core.handler.BaseHandler;
import tx.squirrel.neko.core.model.Config;
import tx.squirrel.neko.core.model.Session;

class FacebookHandler extends BaseHandler {
	
	public function new(){
		super();
		free("default", "facebook.mtt",	doDefault);
		logged("auth",	"facebook.mtt",	doAuth);
	}
	
	public function doDefault():Void {
		display({
			params:Web.getParams(),
			headers:Web.getClientHeaders(),
			ip:Web.getClientIP(),
			uri:Web.getURI()
		});
	}
	
	public function doAuth() {
		
		var appId:String  = argument(1);
		var authToken:String  = Web.getParams().get("auth_token");
		var app:Application = Application.manager.search({appId:appId}).pop();
		var params:Hash<String> = new Hash<String>();
		Facebook.init(app.apiKey,app.apiSecret);
		var session:Dynamic = Facebook.auth.getSession(authToken);
		
		params.set("authToken", authToken);
		params.set("appId", appId);
		params.set("apiKey", app.apiKey);
		params.set("apiSecret", app.apiSecret);
		
		params.set("sessionId",	session.session_key);
		params.set("sessionUid", session.uid);
		params.set("sessionExpires", session.expires);
		try{
			if (session.expires != null) {
				params.set("sessionExpiresDate", Date.fromTime(Std.parseFloat(session.expires)).toString());
			}
		}catch (er:Dynamic) {}
		display({
			params:params,
			headers:Web.getClientHeaders(),
			ip:Web.getClientIP(),
			uri:Web.getURI()
		});
	}
}